package com.atguigu.test5.test51;

/**
 * @author 路飞
 * @date 2024/4/10 10:34
 * @description 5.	请使用二分查找算法查找字符数组{"a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”}中”g”元素的位置？
 */
public class Test5 {
    public static void main(String[] args) {
        String[] arr = {"a","b","c","d","e","f","g","h"};
        String target = "f";

        System.out.println(target + "在数组中的索引为:" + binarySearch(arr, target));
    }

    public static int binarySearch(String[] arr, String target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (target.equals(arr[mid])) {
                return mid;
            } else if (target.compareTo(arr[mid]) < 0) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}
